<template>
    <view class="page-box">
        <header class="header"></header>
        <section class="section">
            <view class="card">
                <view class="card-title">身份认证</view>
                <view class="upload-container row bothSide verCenter">
                    <view class="upload-box column rowCenter verCenter">
                        <template v-if="form.id_card_front_img">
                            <view class="upload-pic-show row rowCenter verCenter">
                                <image :src="form.id_card_front_img" mode="widthFix" @click="previewChange(form.id_card_front_img)"></image>
                                <view class="delete row rowCenter verCenter" @click="deletePic('id_card_front_img')">
                                    <text class="iconfont icon-shanchu"></text>
                                </view>
                            </view>
                        </template>
                        <template v-else>
                            <view class="upload row rowCenter verCenter v1" @click="vehicleHandle(3)">
                                <text class="iconfont icon-a-tubiaochangyongsousuo1"></text>
                            </view>
                        </template>
                        <text class="tt">点击上传人像面</text>
                    </view>
                    <view class="upload-box column rowCenter verCenter">
                        <template v-if="form.id_card_opposite_img">
                            <view class="upload-pic-show row rowCenter verCenter">
                                <image :src="form.id_card_opposite_img" mode="widthFix" @click="previewChange(form.id_card_opposite_img)"></image>
                                <view class="delete row rowCenter verCenter" @click="deletePic('id_card_opposite_img')">
                                    <text class="iconfont icon-shanchu"></text>
                                </view>
                            </view>
                        </template>
                        <template v-else>
                            <view class="upload row rowCenter verCenter v2" @click="vehicleHandle(4)">
                                <text class="iconfont icon-a-tubiaochangyongsousuo1"></text>
                            </view>
                        </template>
                        <text class="tt">点击上传国微面</text>
                    </view>
                </view>
            </view>
            <view class="card">
                <view class="card-title">行驶证照片</view>
                <view class="form-item" style="margin-top: 28rpx;margin-bottom: 24rpx;">
                    <view class="title required">表显里程：</view>
                    <view class="input-box row">
                        <input type="number" placeholder="请输入车辆仪表盘显示的公里数" placeholder-style="color: #6E767A;" class="uni-input" v-model="form.mileage" />
                    </view>
                </view>
                <view class="upload-container row bothSide verCenter">
                    <view class="upload-box column rowCenter verCenter">
                        <template v-if="form.driving_license_original_img">
                            <view class="upload-pic-show row rowCenter verCenter">
                                <image :src="form.driving_license_original_img" mode="widthFix" @click="previewChange(form.driving_license_original_img)"></image>
                                <view class="delete row rowCenter verCenter" @click="deletePic('driving_license_original_img')">
                                    <text class="iconfont icon-shanchu"></text>
                                </view>
                            </view>
                        </template>
                        <template v-else>
                            <view class="upload row rowCenter verCenter v2" @click="vehicleHandle(1)">
                                <text class="iconfont icon-a-tubiaochangyongsousuo1"></text>
                            </view>
                        </template>
                        <text class="tt">点击上传正本面</text>
                    </view>
                    <view class="upload-box column rowCenter verCenter">
                        <template v-if="form.driving_license_duplicate_img">
                            <view class="upload-pic-show row rowCenter verCenter">
                                <image :src="form.driving_license_duplicate_img" mode="widthFix" @click="previewChange(form.driving_license_duplicate_img)"></image>
                                <view class="delete row rowCenter verCenter" @click="deletePic('driving_license_duplicate_img')">
                                    <text class="iconfont icon-shanchu"></text>
                                </view>
                            </view>
                        </template>
                        <template v-else>
                            <view class="upload row rowCenter verCenter v2" @click="chooseImageChange('driving_license_duplicate_img')">
                                <text class="iconfont icon-a-tubiaochangyongsousuo1"></text>
                            </view>
                        </template>
                        <text class="tt">点击上传副本面</text>
                    </view>
                </view>
            </view>
            <view class="card" style="margin-bottom: 32rpx;">
                <view class="card-title">绑卡信息</view>
                <view class="form-item" style="margin-top: 28rpx;">
                    <view class="title required">银行卡号：</view>
                    <view class="input-box row bothSide verCenter">
                        <input type="number" inputmode="numeric" placeholder="请输入银行卡号" placeholder-style="color: #6E767A;" class="uni-input" v-model="form.bank_card_number" />
                        <text class="iconfont icon-a-tubiaochangyongsousuo1" @click="identifyBankCard()"></text>
                    </view>
                </view>
                <view class="form-item" style="margin-top: 28rpx;">
                    <view class="title required">银行名称：</view>
                    <view class="input-box row bothSide verCenter">
                        <input type="text" placeholder="请输入银行名称" placeholder-style="color: #6E767A;" class="uni-input" v-model="form.bank_card_name" />
                    </view>
                </view>
                <view class="form-item" style="margin-top: 28rpx;">
                    <view class="title required">银行卡关联手机号：</view>
                    <view class="input-box row">
                        <input type="number" inputmode="tel" placeholder="请输入银行卡关联手机号" placeholder-style="color: #6E767A;" class="uni-input" v-model="form.bank_reserve_mobile" />
                    </view>
                </view>
            </view>
            <view class="card" style="margin-bottom: 32rpx;" v-if="checkingSupplyInfo.pre_review_info_annual_income">
                <view class="card-title">预审信息</view>
                <view class="form-item" style="margin-top: 28rpx;" v-if="checkingSupplyInfo.pre_review_info_annual_income">
                    <view class="title required">年收入：</view>
                    <view class="input-box row">
                        <input type="number" placeholder="请输入年收入" placeholder-style="color: #6E767A;" class="uni-input" v-model="form.pre_review_info_annual_income" />
                    </view>
                </view>
                <view class="form-item" style="margin-top: 28rpx;" v-if="checkingSupplyInfo.pre_review_info_loan_purpose">
                    <view class="title required">贷款用途：</view>
                    <view class="input-box row">
                        <input type="text" placeholder="请输入贷款用途" placeholder-style="color: #6E767A;" class="uni-input" v-model="form.pre_review_info_loan_purpose" />
                    </view>
                </view>
                <view class="form-item" style="margin-top: 28rpx;" v-if="checkingSupplyInfo.pre_review_info_loan_cycle">
                    <view class="title required">申请期数：</view>
                    <view class="input-box row">
                        <input type="number" placeholder="请输入申请期数" placeholder-style="color: #6E767A;" class="uni-input" v-model="form.pre_review_info_loan_cycle" />
                    </view>
                </view>
                <view class="form-item" style="margin-top: 28rpx;" v-if="checkingSupplyInfo.pre_review_info_loan_address">
                    <view class="title required">申请城市：</view>
                    <view class="dropdown row bothSide verCenter">
                        <view class="dropdown-wrap">
                            <view class="dropdown-wrap">
                                <uni-data-picker :localdata="region" placeholder="请选择所在城市" popup-title="请选择城市" v-model="address" @change="onchange" @nodeclick="onnodeclick($event, 1)"></uni-data-picker>
                            </view>
                        </view>
                        <text class="dropdown-ico"></text>
                    </view>
                </view>
                <view class="form-item" style="margin-top: 28rpx;" v-if="checkingSupplyInfo.pre_review_info_loan_address">
                    <view class="title required">详细地址：</view>
                    <view class="input-box row">
                        <input type="text" placeholder="请输入详细地址" placeholder-style="color: #6E767A;" class="uni-input" v-model="form.pre_review_info_loan_address_detail" />
                    </view>
                </view>
            </view>
            <view class="btn row rowCenter verCenter" @click="submit">提 交</view>
        </section>
    </view>
</template>

<script>
    import { API } from '@/util/api.js';

    export default {
        data() {
            return {
                region: [], //城市列表
                address: 0,
                order_id: '',
                car_valuation: '', //车辆估值
                checkingSupplyInfo: {}, //验证只管是否配置显示
                form: {
                    "order_id": "",
                    "id_card_front_img": "", //身份证-正面
                    "id_card_opposite_img": "", //身份证-反面
                    "driving_license_original_img": "", //行驶证-正本
                    "driving_license_duplicate_img": "", //行驶证-副本
                    "mileage": "", //表显里程
                    "vehicle_condition_price": "",
                    "bank_card_img": "", //银行卡图片
                    "bank_card_number": "", //银行卡号码
                    "bank_reserve_mobile": "", //银行卡关联手机号
                    "bank_card_name": "", //银行名称
                    "car_no": "",
                    "vehicle_brand": "",
                    "vehicle_first_registration_date": "",
                    "vehicle_vin": "",
                    "vehicle_owner_id_card_name": '',
                    "vehicle_owner_id_card": "",
                    "vehicle_engine_no": "",//发动机号码
                    //4.0新增地址
                    "vehicle_license_organ": '', //车辆上牌发证机关
                    "id_card_expiration_date": '', //身份证有效期
                    "id_card_license_organ": '', //身份证发证机关
                    "id_card_license_ethnicity": '', //身份证民族
                    "vehicle_owner_register_address": '', //车主户籍地址
                    "vehicle_owner_birth_date": '', //车主出生日期
                    "pre_review_info_annual_income": '', //预审信息-年收入
                    "pre_review_info_loan_purpose": '', //预审信息-贷款用途
                    "pre_review_info_loan_cycle": '', //预审信息-申请期数
                    "pre_review_info_loan_address_province_id": '', //预审信息-申请地址-省
                    "pre_review_info_loan_address_city_id": '', //预审信息-申请地址-市
                    "pre_review_info_loan_address_district_id": '', //预审信息-申请地址-区
                    "pre_review_info_loan_address_detail": '' //预审信息-申请地址-详细地址
                }
            };
        },
        onLoad(options) {
            this.form.order_id = options.order_id || '';
            this.getRegion();
            this.getCheckingSupplyInfo();
        },
        onShow() {

        },
        methods: {
            /**
             * 监听城市
             * @param {Object} e
             */
            onchange(e) {

            },
            /**
             * 选择城市
             * @param {Object} node
             * @param {Object} type 
             */
            onnodeclick(node) {
                console.log(node)
                if (node.level == 1) {
                    this.form.pre_review_info_loan_address_province_id = node.value;
                } else if (node.level == 2) {
                    this.form.pre_review_info_loan_address_city_id = node.value;
                } else if (node.level == 3) {
                    this.form.pre_review_info_loan_address_district_id = node.value;
                }
            },
            /**
             * 进件字段配置信息
             */
            getCheckingSupplyInfo() {
                this.request(API.getCheckingSupplyInfo, 'GET', { order_id: this.form.order_id }, true).then(res => {
                    if (res.code === 0) {
                        this.checkingSupplyInfo = res.data;
                        this.getOrderAddedInfo();
                    } else {
                        // 获取信息失败的情况下，直接跳转
                        uni.redirectTo({
                            url: `/pages/order/selfDetail?order_id=${this.form.order_id}`
                        });
                    }
                });
            },
            /**
             * 获取进件已经填写的资料
             */
            getOrderAddedInfo() {
                this.request(API.getOrderAddedInfo, 'GET', { order_id: this.form.order_id }, true).then(res => {
                    // 遍历 res 对象，将除了 order_id 之外的所有字段赋值给 this.form
                    Object.keys(res).forEach(key => {
                        if (key !== 'order_id' && this.form.hasOwnProperty(key)) {
                            this.$set(this.form, key, res[key]);
                        }
                    });
                }).catch(error => {
                    console.error('获取进件资料失败:', error);
                    uni.showToast({
                        title: '获取资料失败，请重试',
                        icon: 'none'
                    });
                });
            },
            /**
             * 获取地址
             */
            getRegion() {
                this.request(API.getRegion, 'GET', { get_pcd: 1 }, true).then(res => {
                    if (res.code === 0) {
                        this.region = res.data[0].children;
                    } else {
                        uni.showToast({
                            title: res.msg,
                            icon: 'none'
                        });
                    }
                });
            },
            /**
             * 识别银行卡
             */
            identifyBankCard() {
                uni.chooseImage({
                    count: 1,
                    sizeType: ['original'],
                    sourceType: ['album', 'camera'],
                    success: chooseImageRes => {
                        console.log('选择图片成功：', chooseImageRes);

                        // 显示loading
                        uni.showLoading({
                            title: '识别银行卡中...'
                        });

                        // 获取选择的图片路径数组
                        const tempFilePaths = chooseImageRes.tempFilePaths;

                        //上传到服务器
                        uni.uploadFile({
                            url: API.uploadImage,
                            filePath: tempFilePaths[0],
                            name: 'file',
                            formData: {
                                'source': 'appUser',
                                'is_use_ocr': 2 //是否使用图片识别，0-否，1-行驶证识别，2-银行卡识别，3-身份证识别
                            },
                            success: uploadFileRes => {
                                console.log('服务器上传图片成功：', uploadFileRes);
                                uni.hideLoading();
                                let data = JSON.parse(uploadFileRes.data);
                                if (data.code === 0) {
                                    this.form.bank_card_number = data.data.card_num; //银行卡号码
                                    this.form.bank_card_img = data.data.file_url; //银行卡图片
                                    this.form.bank_card_name = data.data.bank_name; //银行名称
                                    this.$forceUpdate();
                                } else {
                                    uni.showToast({
                                        title: data.msg,
                                        icon: 'none',
                                        duration: 5000
                                    });
                                }
                            },
                            fail: () => {
                                uni.hideLoading();
                                uni.showToast({
                                    title: '上传图片失败',
                                    icon: 'none'
                                });
                            }
                        });
                    }
                });
            },
            /**
             * @param {Object} type 1 身份证 2行驶证
             */
            vehicleHandle(type) {
                if (type == 1) {
                    if (!this.form.mileage) {
                        uni.showToast({
                            title: '请输入车辆仪表盘显示的公里数',
                            icon: 'none',
                            duration: 5000
                        });
                        return false;
                    }
                }

                uni.chooseImage({
                    count: 1,
                    sizeType: ['original'],
                    sourceType: ['album', 'camera'],
                    success: chooseImageRes => {
                        console.log('选择图片成功：', chooseImageRes);

                        // 显示loading
                        uni.showLoading({
                            title: '识别中...'
                        });

                        // 获取选择的图片路径数组
                        const imagePath = chooseImageRes.tempFilePaths[0]; // 获取选中的图片路径

                        //上传到服务器
                        uni.uploadFile({
                            url: API.uploadImage,
                            filePath: imagePath,
                            name: 'file',
                            formData: {
                                'source': 'appUser',
                                'isNoCheck_12345qwert': '12345_qwert', //去掉防刷验证
                                'is_use_ocr': type, //是否使用图片识别，0-否，1-行驶证识别，2-银行卡识别，3-身份证正面识别，4-身份证背面识别
                                'mileage': this.form.mileage //里程数
                            },
                            success: uploadFileRes => {
                                console.log('服务器上传图片成功：', uploadFileRes);
                                uni.hideLoading();
                                let data = JSON.parse(uploadFileRes.data);
                                if (data.code === 0) {
                                    if (type == 1) {
                                        //行驶证识别
                                        this.form.driving_license_original_img = data.data.file_url; //更新行驶证正面照片
                                        this.form.vehicle_condition_price = data.data.car_prices; //车况给继来用的
                                        this.car_valuation = data.data.car_price; //车辆估值

                                        //新增几个字段
                                        this.form.car_no = data.data.plateNo; //车牌号
                                        this.form.vehicle_brand = data.data.vehicle_brand; //车辆品牌
                                        this.form.vehicle_first_registration_date = data.data.registerDate; //首次上牌日期
                                        this.form.vehicle_vin = data.data.vin; //车辆识别代码
                                        this.form.vehicle_license_organ = data.data.seal; //上牌发证机关
                                        this.form.vehicle_engine_no = data.data.engine_no; //发动机号码
                                    } else if (type == 3) {
                                        //身份证正面识别
                                        this.form.id_card_front_img = data.data.file_url; //身份证-正面文件
                                        this.form.vehicle_owner_id_card_name = data.data.name; //名字
                                        this.form.vehicle_owner_id_card = data.data.idNumber; //身份证号
                                        this.form.id_card_license_ethnicity = data.data.ethnicity; //身份证民族
                                        this.form.vehicle_owner_register_address = data.data.address; //户籍地址
                                        this.form.vehicle_owner_birth_date = data.data.birthDate; //出生日期
                                    } else if (type == 4) {
                                        //身份证背面识别
                                        this.form.id_card_opposite_img = data.data.file_url; //身份证-背面文件
                                        this.form.id_card_expiration_date = data.data.validPeriod; //身份证有效期
                                        this.form.id_card_license_organ = data.data.issueAuthority; //身份证发证机关
                                    }

                                    this.$forceUpdate();
                                } else {
                                    uni.showToast({
                                        title: data.msg,
                                        icon: 'none',
                                        duration: 5000
                                    });
                                }
                            },
                            fail: () => {
                                uni.hideLoading();
                                uni.showToast({
                                    title: '上传图片失败',
                                    icon: 'none'
                                });
                            }
                        });
                    }
                });
            },
            /**
             * 上传图片
             * @param {Object} index
             */
            chooseImageChange(index) {
                uni.chooseImage({
                    count: 1,
                    sizeType: ['original'],
                    sourceType: ['album', 'camera'],
                    success: chooseImageRes => {
                        console.log('选择图片成功：', chooseImageRes);

                        // 显示loading
                        uni.showLoading({
                            title: '上传中...'
                        });

                        // 获取选择的图片路径数组
                        const imagePath = chooseImageRes.tempFilePaths[0]; // 获取选中的图片路径

                        //上传到服务器
                        uni.uploadFile({
                            url: API.uploadImage,
                            filePath: imagePath,
                            name: 'file',
                            formData: {
                                'source': 'appUser'
                            },
                            success: uploadFileRes => {
                                console.log('服务器上传图片成功：', uploadFileRes);
                                uni.hideLoading();
                                let data = JSON.parse(uploadFileRes.data);
                                if (data.code === 0) {
                                    const imageFields = {
                                        'id_card_front_img': 'id_card_front_img',
                                        'id_card_opposite_img': 'id_card_opposite_img',
                                        'driving_license_original_img': 'driving_license_original_img',
                                        'driving_license_duplicate_img': 'driving_license_duplicate_img',
                                        'bank_card_img': 'bank_card_img'
                                    };

                                    if (imageFields[index]) {
                                        this.form[imageFields[index]] = data.data;
                                    }
                                    this.$forceUpdate();
                                } else {
                                    uni.showToast({
                                        title: data.msg,
                                        icon: 'none',
                                        duration: 5000
                                    });
                                }
                            },
                            fail: () => {
                                uni.hideLoading();
                                uni.showToast({
                                    title: '上传图片失败',
                                    icon: 'none'
                                });
                            }
                        });
                    }
                });
            },
            /**
             * 预览图片
             * @param {Object} img
             * @param {Object} index
             */
            previewChange(img) {
                uni.previewImage({
                    urls: [img]
                });
            },
            /**
             * 删除图片
             * @param {Object} index
             */
            deletePic(index) {
                const imageFields = {
                    'id_card_front_img': 'id_card_front_img',
                    'id_card_opposite_img': 'id_card_opposite_img',
                    'driving_license_original_img': 'driving_license_original_img',
                    'driving_license_duplicate_img': 'driving_license_duplicate_img',
                    'bank_card_img': 'bank_card_img'
                };

                if (imageFields[index]) {
                    this.form[imageFields[index]] = '';
                }
            },
            submit() {
                // 检查必填项
                const requiredFields = [
                    { field: 'id_card_front_img', msg: '请上传身份证-正面' },
                    { field: 'id_card_opposite_img', msg: '请上传身份证-反面' },
                    { field: 'mileage', msg: '请输入表显里程' },
                    { field: 'driving_license_original_img', msg: '请上传行驶证-正本' },
                    { field: 'driving_license_duplicate_img', msg: '请上传行驶证-副本' },
                    { field: 'bank_card_number', msg: '请输入银行卡号' },
                    { field: 'bank_card_name', msg: '请输入银行名称' },
                    { field: 'bank_reserve_mobile', msg: '请输入银行卡关联手机号' }
                    // { field: 'pre_review_info_annual_income', msg: '请输入年收入' },
                    // { field: 'pre_review_info_loan_purpose', msg: '请输入贷款用途' },
                    // { field: 'pre_review_info_loan_cycle', msg: '请输入申请期数' },
                    // { field: 'pre_review_info_loan_address_detail', msg: '请输入详细地址' }
                ];

                // 循环检查必填项
                for (var item of requiredFields) {
                    if (!this.form[item.field]) {
                        uni.showToast({
                            title: item.msg,
                            icon: 'none',
                            duration: 5000
                        });
                        return false;
                    }
                }

                // 提交表单
                this.request(API.submitPreReviewAddInfo, 'POST', this.form, true).then(res => {
                    if (res.code === 0) {
                        uni.navigateTo({
                            url: `/pages/order/success?car_valuation=${encodeURIComponent(this.car_valuation)}`
                        });
                    } else {
                        uni.showToast({
                            title: res.msg,
                            icon: 'none',
                            duration: 5000
                        });
                    }
                });
            }
        }
    };
</script>

<style scoped lang="scss">
    @import '@/assets/css/order/preReviewAddInfo.scss';
</style>